package com.software_product_construction.backend_software_product_construction.util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class DataAndMethodUtil {
    /**
     * 表示的是登陆是验证码的有效时长
     */
    private final static long TIMEOUT = 120 * 1000;
    private static boolean codeListenIsRun = false;
    private static Map<String,Object> codeMap = null;

    public static synchronized boolean getCodeListenIsRun(){
        return codeListenIsRun;
    }
    public static synchronized void setCodeListenIsRun(boolean isRun){
        codeListenIsRun = isRun;
    }
    public synchronized static Map<String,Object> getCodeMap(){
        if(codeMap == null){
            codeMap = new HashMap<>();
        }
        return codeMap;
    }

    public synchronized static String getCodeById(String id){
        return (String) getCodeMap().get(id);
    }

    public synchronized static void setCodeById(String id,String code,String timeStrap){
        getCodeMap().put(id, new String[]{code, timeStrap});
    }

    public static synchronized void startListen(){
        if(getCodeListenIsRun()){
            return;
        }else{
            Map<String, Object> map = getCodeMap();
            Thread codeListenThread = new Thread(() -> {
                while(map.size() > 0){
                    Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Map.Entry<String, Object> mapEntity;
                    while(iterator.hasNext()){
                        mapEntity = iterator.next();
                        String[] val = (String[]) mapEntity.getValue();
                        long initTime = Long.parseLong(val[1]);
                        if (System.currentTimeMillis() - initTime > TIMEOUT) {
                            iterator.remove();
                        }
                    }
                }
                setCodeListenIsRun(false);
            });
            codeListenThread.start();
            setCodeListenIsRun(true);
        }
    }
}
